package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.model.entity.UserModel;
import com.example.demo.model.response.UserResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/file")
public class FileController {

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.url}")
    private String uploadUrl;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(MultipartFile file) throws Exception {
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File dest = new File(uploadPath + File.separator + fileName);
        file.transferTo(dest);
        JSONObject result = new JSONObject();
        result.put("file_url", uploadUrl + fileName);
        return result;
    }

}
